// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init()
const db = cloud.database()
const rightCollection = db.collection('right')
const rightinfoCollection = db.collection('rightinfo')
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const righted = event.openid
  let state = 0 // 申请发送成功
  let count = 0 //30天内已经申请的次数
  let createDate

  await rightinfoCollection.where({
    openid: wxContext.OPENID
  }).count().then(res => {
    if(res.total == 0){
      state = 6 //我的互通信息未填写无法发起申请
    }
  })
  if(state == 6) return {state}

  await rightinfoCollection.where({
    openid: righted
  }).count().then(res => {
    if (res.total == 0) {
      state = 7 //对方的互通信息未填写无法发起申请
    }
  })
  if(state == 7) return {state}

  await rightCollection.where({
    righter: wxContext.OPENID,
    righted
  }).get().then(res => {
    if(res.data.length != 0){
      count = res.data[0].count
      createDate = res.data[0].createDate
      if (res.data[0].status == 2){
        state = 2 //对方已经同意了上一次申请
      } else if (res.data[0].status == 3){
        state = 3 //对方已经拒绝了上一次申请 提示剩余申请次数
      }else{
        state = 1 //之前已经申请过了 正在申请中
      }
    }
  })
  if (count >= 3 && (new Date().getTime() - createDate) < 30 * 24 * 3600 * 1000){
    return {
      state: 4 //已超出次数限制
    }
  } else if ((new Date().getTime() - createDate) > 30 * 24 * 3600 * 1000){
    await rightCollection.where({
      righter: wxContext.OPENID,
      righted
    }).update({
      data: {
        count: 1,
        createDate: new Date().getTime()
      }
    })
  }
  if (state == 1 || state == 2) return {state}

  if(state == 3) {
    await rightCollection.where({
      righter: wxContext.OPENID,
      righted
    }).update({
      data: {
        count: _.inc(1),
        applyDate: new Date().getTime(), //最近一次发出申请的时间
        status: 1 //1:申请中 2:已同意 3:已拒绝
      }
    })
    return {
      state,
      restCount: 3 - count -1
    }
  }

  await rightCollection.where({
    righter: righted,
    righted: wxContext.OPENID
  }).get().then(res => {
    if(res.data.length != 0){
      state = 5 //对方曾对我发起过申请 提示是否可以直接同意该次申请
    }
  })

  if(state == 5){
    await rightCollection.where({
      righter: righted,
      righted: wxContext.OPENID
    }).update({
      data: {
        applyDate: new Date().getTime(), //最近一次发出申请的时间
        status: 2 //1:申请中 2:已同意 3:已拒绝
      }
    })
    return { state }
  } 

  await rightCollection.add({
    data: {
      righter: wxContext.OPENID,
      righted,
      count: 1,
      createDate: new Date().getTime(), //创建时间 用来做一个月申请次数的限制 3次
      applyDate: new Date().getTime(), //最近一次发出申请的时间
      status: 1 //1:申请中 2:已同意 3:已拒绝
    }
  })

  return {
    state,
    restCount: 2
  }
}